var util = require('../../utils/util.js');
var WxParse = require('../../wxParse/wxParse.js');
var qcloud = require('../../vendor/wafer2-client-sdk/index')
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isHaveResume: null,
    submitText: '',
    submitdisabled: false,
    mode: true,
    animationData: {},
    height: "100%",
    positionInfo:{},
    similarPosiInfo:{},
    yingpinBtn: { text: "我要申请", disabled:false},
    successlabel:"",
    nonet: true 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var positionId = options.pid;
    var posiname = options.posiname;
    var that = this;
      util.post(app.api.getPositionDetail, { jobid: positionId},function(res){
      //获取职位详情
      that.setData({
        positionInfo: res.data
      });
      WxParse.wxParse('article', 'html', that.data.positionInfo.majorDuty, that, 5);

      //判断是否有简历
      if (app.globalData.openid != null) {
        util.post(app.api.isHaveResume, { unionid: app.globalData.unionid }, function (res) {
         // if (res.data != null) {
            that.setData({
              isHaveResume: res.data
            });
            wx.setStorageSync('isHaveResume', that.data.isHaveResume);
          //}
        });
      }
      if (that.data.isHaveResume=== null) {
        that.setData({
          submitText: "请先完善您的个人资料",
          isHaveResume: false
        });
      } else {
        that.setData({
          submitText: "发送资料",
          isHaveResume: true
        });
      }
      //判断是否已投递过
      try {
        var sendPosiArray = wx.getStorageSync('sendPosiArray')
        if (sendPosiArray) {
          // Do something with return value
          for (var i = 0; i < sendPosiArray.length; i++) {
            if (sendPosiArray[i] == app.globalData.positionDetail.id) {
              that.setData({
                submitText: "已申请",
                'yingpinBtn.disabled': true
              });
            }
          }

        }
      } catch (e) {
        // Do something when catch error
      }

    });
    // console.log("openid=" + app.globalData.unionid);
    // console.log("jobid=" +positionId);
  
    util.post(app.api.isExistRec, { unionid: app.globalData.unionid,jobid: positionId},function(res){
      if (res.data == "hasRec"){
          //已经应聘该职位
        that.setData({
          yingpinBtn: { text: "已申请", disabled: true }
        });
      } else if (res.data =="notRec"){
        //未应聘该职位
        that.setData({
          yingpinBtn: { text: "我要申请", disabled: false }
        });
      }else{
        that.setData({
          isHaveResume: false
        });
      }
      
    });
   
},

  //保存推送码
  saveFormIds:function(){
    var formIds=app.globalData.globalFormIds;//获取globalFormIds
    if(formIds!=null){
      formIds=JSON.stringify(formIds);
      app.globalData.globalFormIds='';
    }
    util.post(app.api.saveFormIds, { unionid: app.globalData.unionid, openid: app.globalData.openid, formids:formIds,type:2},function(res){
    });
  },
  collectFormIds: function (formId) {
    var formIds = app.globalData.globalFormIds;
    if (!formIds) {
      formIds = [];
    }
    var data = { formId: formId, expire: parseInt(new Date().getTime() / 1000) + 604800 }
    formIds.push(data);
    app.globalData.globalFormIds = formIds;//保存推送码并赋值给变量
    wx.setStorageSync("globalFormIds", formIds)
  },

  formSubmit: function (e) {
    var formId = e.detail.formId;
    this.collectFormIds(formId);//保存推送码
    //上传保存推送码
    this.saveFormIds();
  },

  //公司详情
  companyDetailTap: function (event) {
     var id = event.currentTarget.dataset.pid; // 当前id
     wx.navigateTo({
       url: '../company-detail/company-detail?id=' + id
     });
   },

  //发送简历
  isSendTap: function (e) {
    var that = this;
    var formId = e.detail.formId;
    // console.log("formId=" + formId);
    // console.log(that.data.yingpinBtn);
    // console.log(that.data.isHaveResume);
    if (app.globalData.openid != null && !(that.data.isHaveResume == null || that.data.isHaveResume == 'binded' || that.data.isHaveResume == 'generated')) {
      wx.showModal({
        title: '发送确认',
        content: '发送后不可撤回，确认发送？',
        cancelText: '取消',
        cancelColor: '#999',
        confirmText: '确认',
        confirmColor: '#4990E2',
        success: function (res) {
          if (res.confirm) {
            app.loading();
            that.sendResumeFun(formId);
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }else {
      if (that.data.isHaveResume == null || that.data.isHaveResume == 'binded' || that.data.isHaveResume =='generated') {
        wx.showModal({
          title: '完善资料',
          content: '请完善您的资料',
          success: function (res) {
            if (res.confirm) {
              wx.reLaunch({
                //url: '/pages/user/index',
                url: '/pages/web-view/web-view'
                // url: '/pages/edit-resume-base/edit-resume-base?type=0',
              });
            } else if (res.cancel) {
            }
          }
        })
      }else{
        wx.showModal({
          title: '请先登录',
          content: '请微信授权登录,并完善您的资料',
          cancelText: '取消',
          cancelColor: '#999',
          confirmText: '确认',
          confirmColor: '#4990E2',
          success: function (res) {
            if (res.confirm) {
              app.loading();
              //that.sendResumeFun();
              wx.reLaunch({
                url: '/pages/user/index',
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    }

  },

  moreposi: function () {
    wx.navigateBack({
      url: '/pages/home/home',
    })
  },

  //投递接口
  sendResumeFun: function (formId) {
    var that = this;
    util.post(app.api.deliveryResume, {
      jobid: that.data.positionInfo.id,
      unionid: app.globalData.unionid,
      openid:app.globalData.openid,
      formid:formId
    }, function (data) {
      if (data.code == "200") {
        that.setData({
          height: "",
          successlabel:data.msg
        });
        var animation = wx.createAnimation({
          duration: 1000,
          timingFunction: 'ease',
        })

        that.setData({
          mode: false,
          animationData: animation.export(),
          //similarPosi: data.ret,
          submitText: "已申请",
          'yingpinBtn.disabled':true,
        })
        //缓存申请过的职位id
        try {
          var sendPosiArray = wx.getStorageSync('sendPosiArray')
          if (sendPosiArray) {
            // Do something with return value
            sendPosiArray.push(that.data.positionInfo.id);
            wx.setStorageSync('sendPosiArray', sendPosiArray);
          } else {
            var sendPosiArray = [];
            sendPosiArray.push(that.data.positionInfo.id);
            wx.setStorageSync('sendPosiArray', sendPosiArray);
          }
        } catch (e) {
          // Do something when catch error
        }
      } else {
        app.alert(data.msg);
      }
      app.hideloading();
    });
    //更多职位
    util.post(app.api.similarPosi, { unionid: app.globalData.unionid, jobid: that.data.positionInfo.id}, function (res) {
      that.setData({
        similarPosiInfo: res.data
      });
    });

  },

  //职位详情
  positionDetailTap: function (event) {
    var id = event.currentTarget.dataset.id; // 当前id
    // var position = null;
    // // 找出当时点击的那一项的详细信息
    // for (var d of this.data.similarPosi) {
    //   if (d.id == id) {
    //     position = d;
    //     break;
    //   }
    // }
    // if (!position) {
    //   console.log('系统出错');
    //   return;
    // }
    // 设置到全局变量中去，让下个页面可以访问
    // app.globalData.positionDetail = position;
    // 切换页面
    wx.navigateTo({
      url: '../position-detail/position-detail?pid=' + id
    });
  },

  recommandTap: function (event) {
    var that=this;
    if (app.globalData.openid != null &&!(that.data.isHaveResume == null || that.data.isHaveResume == 'binded' || that.data.isHaveResume == 'generated')) {
        var animation = wx.createAnimation({
          duration: 1000,
          timingFunction: 'ease',
        })
        wx.navigateTo({
          mode: false,
          animationData: animation.export(),
          url: '../position-recommand/position-recommand?position=' + JSON.stringify(this.data.positionInfo)
        });
      
    }else{
      if (that.data.isHaveResume == null || that.data.isHaveResume == 'binded' || that.data.isHaveResume == 'generated') {
        wx.showModal({
          title: '完善资料',
          content: '请完善您的资料',
          success: function (res) {
            if (res.confirm) {
              wx.reLaunch({
                //url: '/pages/user/index',
                url: '/pages/web-view/web-view'
                // url: '/pages/edit-resume-base/edit-resume-base?type=0',
              });
            } else if (res.cancel) {

            }
          }
        })
      } else {
        wx.showModal({
          title: '请先登录',
          content: '请微信授权登录,并完善您的资料。',
          cancelText: '取消',
          cancelColor: '#999',
          confirmText: '确认',
          confirmColor: '#4990E2',
          success: function (res) {
            if (res.confirm) {
              app.loading();
              //that.sendResumeFun();
              wx.reLaunch({
                url: '/pages/user/index',
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    }
  },
  //关闭成功提示
  closeTap: function () {
    this.setData({
      mode: true,
      height: "100%"
    })
  },
//已申请职位提示
  myPosiTap:function(){
    wx.navigateTo({
      url: '/pages/my-position/my-position'
    });
  },

  //分享
  onShareAppMessage: function (res) {
    var that = this;
    if (res.from === 'button') {
      // 来自页面内转发按钮
    }
    var title = that.data.positionInfo.companyName + ' 招聘 ' + that.data.positionInfo.name;
    return {
      title: title,
      path: 'pages/position-detail/position-detail?pid=' + that.data.positionInfo.id,
      data: that.data.positionInfo,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  onShow:function(){
    var that=this;
    wx.getNetworkType({
      success: function (res) {
        // 返回网络类型, 有效值：
        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        var networkType = res.networkType
        if (networkType=="none"){
          that.setData({
            nonet: false,
            'yingpinBtn.disabled': true,
            submitdisabled: true
          })
        }
      }
    })
  }

})